﻿using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Quartz;

namespace WebIM.API.Schedules.Quartz
{
    /// <summary>
    /// Quartz 作业执行器
    /// </summary>
    public class QuartzJobRunner : IJob
    {
        private readonly IServiceProvider _serviceProvider;

        /// <summary>
        /// 构造作业执行器
        /// </summary>
        /// <param name="serviceProvider"></param>
        public QuartzJobRunner(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 执行具体的作业计划
        /// </summary>
        /// <param name="context">context</param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            // Scope 作用域
            using (var scope = _serviceProvider.CreateScope())
            {
                var jobType = context.JobDetail.JobType;
                if (scope.ServiceProvider.GetRequiredService(jobType) is IJob job)
                {
                    await job.Execute(context);
                }
            }
        }
    }
}